"""
    @Author  ：思念 
    @File    ：7.jsonpath进阶使用.py
    @Date    ：2024/12/6 9:42 
"""
import jsonpath

info = {
    "store": {
        "book": [
            {"category": "reference",
             "author": "Nigel Rees",
             "title": "Sayings of the Century",
             "price": 8.95
             },
            {"category": "fiction",
             "author": "Evelyn Waugh",
             "title": "Sword of Honour",
             "price": 12.99
             },
            {"category": "fiction",
             "author": "Herman Melville",
             "title": "Moby Dick",
             "isbn": "0-553-21311-3",
             "price": 8.99
             },
            {"category": "fiction",
             "author": "J. R. R. Tolkien",
             "title": "The Lord of the Rings",
             "isbn": "0-395-19395-8",
             "price": 22.99
             }
        ],
        "bicycle": {
            "title": "凤凰",
            "color": "red",
            "price": 19.95
        }
    }
}

# 1.提取第一本书的title
title = jsonpath.jsonpath(info, '$..title')[0]
print(title)

# 2.提取2,3,4的书籍名称
titles = jsonpath.jsonpath(info, '$..book[1:4].title')  # 切片方式
print(titles)
titles = jsonpath.jsonpath(info, '$..book[1,2,3].title')  # 索引方式
print(titles)

# 3.提取第一本和三本书的title
titles = jsonpath.jsonpath(info, '$..title')[::2]
print(titles)
titles = jsonpath.jsonpath(info, '$..book[0,2].title')
print(titles)

# 4.提取最后一本书的title
title = jsonpath.jsonpath(info, '$..book[-1:].title')
print(title)
title = jsonpath.jsonpath(info, '$..book[(@.length-1)].title')
print(title)

# 5.提取价格小于10的书籍
books = jsonpath.jsonpath(info, '$..book[?(@.price<10)].title')
print(books)

# 6.提取价格小于等于20的所有商品
goods = jsonpath.jsonpath(info, '$..*[?(@.price<=20)].title')
print(goods)

# 7. 获取所有书的作者
authors = jsonpath.jsonpath(info, "$..author")
print(authors)
authors = jsonpath.jsonpath(info, "$.store.book[::].author")
print(authors)
authors = jsonpath.jsonpath(info, "$.store.book[*].author")
print(authors)

# 8.获取所有商品
goods = jsonpath.jsonpath(info, "$..store")
print(goods)

# 9. 获取所有商品（包括书、自行车）的价格
prices = jsonpath.jsonpath(info, "$..price")
print(prices)

# 10. 获取带有isbn的书
isbn = jsonpath.jsonpath(info, "$..book[?(@.isbn)]")
print(isbn)

# 11. 获取不带有isbn的书
isbn = jsonpath.jsonpath(info, "$..book[?(!@.isbn)]")
print(isbn)

# 12. 获取价格在5~10之间的书
books = jsonpath.jsonpath(info, "$..book[?(@.price>5 and @.price<10)]")
print(books)
books = jsonpath.jsonpath(info, "$..book[?(@.price>5 && @.price<10)]")
print(books)

# 13. 获取价格不在5~10之间的书
books = jsonpath.jsonpath(info, "$..book[?(@.price<5 || @.price>10)]")
print(books)

print("\n14")
# 14.获取所有的元素
all_element = jsonpath.jsonpath(info, "$.*")
print(all_element)
# 获取全部数据，并将value提取出来
all_element = jsonpath.jsonpath(info, "$..*")
for element in all_element:
    print(element)